package com.lv.suyiyong.hfr.ui

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.SwipeCatpchaDialog
import com.lv.common.im.GenerateTestUserSig
import com.lv.common.imp.OnViewClickListener
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.ktx.setSafeListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.LiveEventUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.TimerUnit
import com.lv.common.utils.YgxNetUtilsKt
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.BindPhoneReqBody
import com.lv.service.net.SendCodeBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.bean.TokenBean
import com.lv.suyiyong.hfr.databinding.ActivityBindPhoneBinding
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * 作者： ygx
 * 创建日期：2023/3/2 7:26 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：绑定手机号 三方登录 微信 0 qq 1 支付宝 2
 */
@Route(path = ARoutUtils.BindPhoneActivity)
class BindPhoneActivity : BaseActivity<ActivityBindPhoneBinding>(), View.OnClickListener {
    @Autowired(name = "openId")
    @JvmField
    var openId: String = ""

    @Autowired(name = "code")
    @JvmField
    var code: String = ""

    @Autowired(name = "name")
    @JvmField
    var mThreedName: String = ""

    @Autowired(name = "logo")
    @JvmField
    var mThreedLogo: String = ""

    private var timer: TimerUnit? = null
    private val viewModelService: ServiceViewModel by viewModel()
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    override fun getLayoutRes() = R.layout.activity_bind_phone
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            vm = mEditorViewModel
            StatusBarUtil.setHeightAndPadding(this@BindPhoneActivity, titleBar)
            mBinding.titleBar.onClickBackIcon { finish() }
            mBinding.titleBar.setTitle("绑定手机号")
            initSingleClickListener(tvCode,btnLogin)

        }
    }

    private fun bindingUser(body: BindPhoneReqBody) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    viewModelService.bindingUser(body)
                }.await()
            parseBindingUserResult(result)
        }

    }

    private fun parseBindingUserResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                login(data)

            }
            onBizError<TokenBean> { code, message, data ->

            }
        }
    }

    private fun showSwipecaptDialog(phone: String) {
        val swipeCatpchaDialog =
            SwipeCatpchaDialog(this, true, true) {
                val sendCode = YgxNetUtilsKt.sendCode(phone)
                sendCode(SendCodeBody(phone, sendCode))
            }
        swipeCatpchaDialog.show()
    }

    private fun sendCode(phone: SendCodeBody) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    viewModelService.sendCode(phone)
                }.await()
            parseSendCodeResult(result)
        }

    }

    private fun parseSendCodeResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (timer == null) {
                    timer = TimerUnit(mBinding.tvCode)
                }
                timer?.startTime()
                message?.let { message ->
                    showToast(this@BindPhoneActivity, message)
                }

            }
            onBizError<TokenBean> { code, message, data ->

            }
        }
    }

    override fun initConfig() {
        super.initConfig()
        LogUtils.e("openid==$openId   code==$code")

    }

    private fun login(res: UserInfo?) {
        res?.let {
            YgxUtilsKt.setAppToken(it.token, it.refreshtoken, it.id)
            // 在用户 UI 点击登录的时候调用
            TUILogin.login(
                this@BindPhoneActivity,
                GenerateTestUserSig.SDKAPPID,
                it.txaccid,
                it.txaccidpassword,
                object : TUICallback() {
                    override fun onError(code: Int, desc: String) {
                        LogUtils.e("onError")
                    }

                    override fun onSuccess() {
                        LiveEventBus
                            .get(LiveEventUtils.FINISH_LOGINACTIVITY_KEY, String::class.java)
                            .post("1")
                        YgxUtilsKt.sendMessgeToSelf(it.txaccid, it.phone)
                        UserDbHelper.insertUserInfo(this@BindPhoneActivity, res)
                        LogUtils.e("onSuccess")
                        finish()
                    }
                })
        }
    }

    override fun initData() {
        super.initData()
    }

    override fun initEvents() {
        super.initEvents()
        mBinding.etPhone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                mBinding.etPhone.paint.isFakeBoldText = !TextUtils.isEmpty(s)
                if (s.length == 11) {
                    mBinding.etCode.requestFocus()
                }

            }

            override fun afterTextChanged(s: Editable) {
            }
        })
    }


    override fun onClick(v: View?) {
       when(v?.id){
           R.id.tv_code->{
               val phone = mEditorViewModel.obMobile.get()
               if (phone.isNullOrEmpty() || phone.length < 11) {
                   showToast(this@BindPhoneActivity, "请输入11位手机号")
               } else {
                   showSwipecaptDialog(phone)
               }
           }
           R.id.btn_login->{
               val bindPhoneReqBody = BindPhoneReqBody(
                   mEditorViewModel.obMobile.get(),
                   mEditorViewModel.obPassword.get()!!,
                   openId,
                   code,
                   mThreedName, mThreedLogo
               )
               bindingUser(bindPhoneReqBody)
           }
       }
    }


}